﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using U.Comm;

namespace U.Web
{
    /// <summary>
    /// 将文件上传到系统临时文件夹，可用于Web，注意可能产生的权限问题
    /// </summary>
    public class TemporaryStorage
    {
        public static string SaveFile(byte[] data)
        {
            string filepath = null;
            bool ok = false;
            FileInfo file = new FileInfo(Path.GetTempFileName());
            filepath = file.FullName;
            FileStream fs = file.Create();
            ok = fs != null;
            try
            {
                fs.Write(data, 0, data.Length);
            }
            catch
            {
                ok = false;
            }
            finally
            {
                if (fs != null) fs.Close();
            }
            return ok ? filepath : null;
        }

        public static byte[] ReadFile(string filepath)
        {
            byte[] content = null;
            if (File.Exists(filepath))
            {
                content = File.ReadAllBytes(filepath);
            }
            return content;
        }

        public static ResultInfo RemoveFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    File.Delete(filePath);
                    return ResultInfo.ReturnSucceed();
                }
                catch (Exception ex)
                {
                    return new ResultInfo() { IsSucceed = false, Message = ex.Message };
                }
            }
            return new ResultInfo() { IsSucceed = false, Message = "指定文件不存在。" };
        }
    }
}
